<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      v-show="showSearch"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="社区名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入社区名称"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
          @clear="resetQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >查询</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['communityInfo:community:add']"
          >新增</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="tableList" border>
      <el-table-column label="序号" type="index" align="center" width="70" />
      <el-table-column
        label="社区名称"
        prop="name"
        :show-overflow-tooltip="true"
        align="center"
      />
      <el-table-column
        label="详细地址"
        prop="address"
        :show-overflow-tooltip="true"
        align="center"
        min-width="100"
      />
      <el-table-column label="经纬度" align="center">
        <template #default="scope">
          {{ scope.row.lnt }} / {{ scope.row.lat }}
        </template>
      </el-table-column>
      <el-table-column
        label="打卡范围（米）"
        align="center"
        prop="clockInRange"
        width="120"
      />
      <el-table-column label="创建日期" align="center" prop="createTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            text
            @click="handleUpdate(scope.row)"
            v-hasPermi="['communityInfo:community:edit']"
          >
            编辑
          </el-button>

          <el-button
            link
            type="primary"
            text
            @click="handleDelete(scope.row)"
            v-hasPermi="['communityInfo:community:remove']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="35vw"
      align-center
      append-to-body
    >
      <el-form
        ref="communityRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="社区名称" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入社区名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input
            v-model="form.address"
            placeholder="请输入详细地址"
            clearable
          >
            <!-- <template #append>
              <el-button type="primary" @click="amapVisible = true"
                >地图</el-button
              >
            </template> -->
          </el-input>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="经度" prop="lnt">
              <el-input
                v-model="form.lnt"
                placeholder="请输入经度"
                type="number"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度" prop="lat">
              <el-input
                v-model="form.lat"
                placeholder="请输入纬度"
                type="number"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="打卡范围" prop="clockInRange">
          <el-input
            v-model.number="form.clockInRange"
            placeholder="请输入打卡范围值"
            type="number"
            clearable
            :min="0"
          >
            <template #append>
              <el-button type="primary">米</el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">保 存</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 地图组件 -->
    <gao-amap
      :isShow="amapVisible"
      :defaultAddress="form.address"
      :defaultPoint="[]"
      @getPosition="getPosition"
    ></gao-amap>
  </div>
</template>

<script setup name="Community">
import {
  listCommunity,
  addCommunity,
  updateCommunity,
  delCommunity,
  getCommunityById,
} from "@/api/community/community";
import GaoAmap from "@/components/Amap";
import { number } from "echarts";

const { proxy } = getCurrentInstance();

const tableList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const title = ref("");
const amapVisible = ref(false);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
  },
  rules: {
    name: [{ required: true, message: "社区名称不能为空", trigger: "blur" }],
    address: [{ required: true, message: "详细地址不能为空", trigger: "blur" }],
    lnt: [
      {
        required: true,
        message: "请填写经度值",
        // message: "请从地图中选择地点经纬度值",
        trigger: "blur",
      },
    ],
    lat: [
      {
        required: true,
        message: "请填写纬度值",
        // message: "请从地图中选择地点经纬度值",
        trigger: "blur",
      },
    ],
    clockInRange: [
      { required: true, message: "打卡范围不能为空", trigger: "blur" },
      {
        validator: (rule, value, callback) => {
          if (value < 0) {
            callback(new Error("打卡范围不可为负值"));
          } else {
            callback();
          }
        },
        trigger: "blur",
      },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询角色列表 */
function getList() {
  loading.value = true;
  listCommunity(queryParams.value).then((response) => {
    const { data } = response;
    tableList.value = data.records ?? [];
    total.value = data.total;
    loading.value = false;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 删除按钮操作 */
function handleDelete(row) {
  const communityIds = row.id;
  proxy.$modal
    .confirm(
      "确认删除该数据？若确认删除请联系管理员重新生成打卡二维码",
      "删除确认"
    )
    .then(function () {
      return delCommunity(communityIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 重置新增的表单以及其他数据  */
function reset() {
  form.value = {
    id: undefined,
    name: undefined,
    address: undefined,
    lnt: undefined,
    lat: undefined,
    clockInRange: 50,
  };
  proxy.resetForm("communityRef");
}

/** 添加角色 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加社区信息";
}

/** 修改角色 */
function handleUpdate(row) {
  reset();
  getCommunityById(row.id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "社区信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["communityRef"].validate((valid) => {
    if (valid) {
      form.value.lat = form.value.lat - 0;
      form.value.lnt = form.value.lnt - 0;
      if (form.value.id != undefined) {
        updateCommunity(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCommunity(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

const getPosition = (point, address) => {
  amapVisible.value = false;
  if (point.length) {
    form.value.lnt = point[0];
    form.value.lat = point[1];
    form.value.address = address;
  }
};
getList();
</script>
